<template>
	<el-popover placement="bottom-end" popper-class="padding-no mp-micro" width="580" v-model="popoverShow" trigger="click" class="filter-reference">
		<el-button slot="reference" :icon="searchType.type === 'search' ? 'iconfont iconshaixuan2-xian aa' : 'iconfont iconshaixuan2-xian'" class="filter-btn" :type="searchType.className" :class="searchType.type" size="medium">
			{{filterName}}
      <baseIcon v-if="searchType.type === 'search'" type="V7_iconV7tubiao_guanbi" @click.native.stop="close"></baseIcon>
		</el-button>
    <portal to="header-btn">
        <i class="V7_iconfont V7_iconV7tubiao_guanbi" v-if="searchType.type === 'search'" @click.native.stop="close"></i>
      </portal>
		<conditionEditor :editCondition="editCondition" ref="conditionEditor" class="wrap" v-if="editCondition.id" @search="search" :filterFieldList="filterFieldList" :updateBaseInfo="updateBaseInfo" :back="back" :handleCommand="handleCommand">
			<div class="filter-title">
				<span class="opacity80 font16">筛选</span>
				<i class="V7_iconfont V7_iconV7tubiao_guanbi pointer opacity60" @click.stop="popoverShow = false"></i>
			</div>
		</conditionEditor>
		<ul v-else-if="searchType.type === 'common'" style="padding-top: 8px">
			<div class="menu-category" v-if="filterData.my.length">
				我的筛选条件
			</div>
			<li class="el-dropdown-menu__item" v-for="item in filterData.my" :key="item.id" @click.stop="searchById(item)">
				<span>{{ item.filterName }}</span>
				<i class="fr el-icon-menu" @click.native.stop="filterDetail(item)"></i>
			</li>
			<div class="menu-category" v-if="filterData.common.length">
				公共筛选条件
			</div>
			<li class="el-dropdown-menu__item" v-for="item in filterData.common" :key="item.id" @click.stop="searchById(item)">
				<span>{{ item.filterName }}</span>
				<i class="el-icon-menu" @click.native.stop="filterDetail(item)"></i>
			</li>
			<li class="el-dropdown-menu__item el-dropdown-menu__item--divided" :key="item.id" @click.stop="searchById(custom)">
				<span>自定义筛选</span>
			</li>
		</ul>
		<div class="wrap" v-else>
			<div class="filter-title">
				<span class="opacity80 font16">筛选</span>
				<i class="el-icon-close pointer opacity60" @click.stop="popoverShow = false"></i>
			</div>
			<conditionForm :fieldsList="filterFieldList" :conditonList="custom.filters" class="condition" type="filter">
			</conditionForm>
			<div class="footer" v-if="custom.filters && custom.filters.length">
				<!-- <el-button size="small" @click.stop="saveDialog">保存条件w</el-button> -->
				<div class="fr">
					<el-link :underline="false" @click.stop="reset" class="margin-r-16">重置</el-link>
					<el-button type="primary" class="screen-button" size="small" @click.stop="search(custom)">确认</el-button>
				</div>
			</div>
			<el-collapse class="collapse" v-model="collapseOpen" v-if="length">
				<el-collapse-item :title="length + '条筛选条件'" name="1">
					<div class="opacity60 margin-b-8" v-if="filterData.my.length">
						我的筛选条件
					</div>
					<div class="btn-group">
						<div class="condtion-btn pointer" v-for="item in filterData.my" :key="item.id">
							<span class="name" @click.stop="searchById(item)">{{ item.filterName }}</span>
							<el-dropdown placement="bottom" trigger="click" @command="handleCommand(item, $event)">
								<i class="iconfont icongengduo-heng rotate90"></i>
								<el-dropdown-menu slot="dropdown" class="mp-micro">
									<el-dropdown-item command="edit">编辑</el-dropdown-item>
									<el-dropdown-item command="copy">复制</el-dropdown-item>
									<el-dropdown-item command="common">设为公共筛选</el-dropdown-item>
									<el-dropdown-item command="delete">删除</el-dropdown-item>
								</el-dropdown-menu>
							</el-dropdown>
						</div>
					</div>
				</el-collapse-item>
			</el-collapse>
			<el-dialog class="mp-micro" title="保存筛选条件" :append-to-body="false" :wrapperClosable="false" :modal-append-to-body="false" :visible.sync="dialogObj.visible" width="480px">
				<el-form ref="form" :model="dialogObj.form" size="small" @submit.native.prevent label-position="top" :rules="rules">
					<el-form-item label="筛选条件名称" prop="filterName">
						<el-input type="text" maxlength="20" v-model="dialogObj.form.filterName"></el-input>
					</el-form-item>
					<el-form-item label="使用范围">
						<el-radio-group v-model="dialogObj.form.useScope">
							<el-radio :label="1">
								个人
							</el-radio>
						</el-radio-group>
					</el-form-item>
				</el-form>
				<template v-slot:footer>
					<el-button @click.stop="dialogObj.visible = false" size="small">取消</el-button>
					<el-button type="primary" @click.stop="submitSave" size="small" class="primary">保存</el-button>
				</template>
			</el-dialog>
		</div>

	</el-popover>
</template>
<script lang="ts">
import { Component, Vue, Ref, Prop, Provide, Watch } from 'vue-property-decorator';
import conditionForm from './conditionForm.vue';
import conditionEditor from './conditionEditor.vue';
import baseIcon from './baseIcon.vue'
// import * as sheetAPI from '@/apis/sheet';
// eslint-disable-next-line no-restricted-imports
import { flatten } from 'lodash';
import { getOption, isValide } from './common';
import { emitter } from '@/afterSales/utils/mmit';
// 自定义筛选
const emptyConditon = {
  filterName: '自定义筛选',
  filters: [],
  id: 'custom'
};
@Component({
  name: 'conditionFilter',
  components: {
    baseIcon,
    conditionForm,
    conditionEditor
  }
})
export default class extends Vue {
  @Prop({ default: () => ([]) }) public filterFieldList!: any;
  [x: string]: any;
  public popoverShow = false;

  public dialogObj = {
    visible: false,
    form: {
      filterName: '',
      useScope: 1
    }
  };

  public rules = {
    filterName: [{ required: true, trigger: 'blur', message: '必填' }]
  };

  @Ref() private conditionEditor!: conditionEditor;
  @Prop({ default: '' }) private worksheetId!: string;
  @Provide() private quick = true;
  private collapseOpen = '';
  // 编辑筛选项
  private editCondition: any = { filters: [] };
  // 处于激活筛选项
  private currentActive: any = {};
  private custom = {
    filterName: '自定义筛选',
    filters: [[getOption()]],
    id: 'custom'
  };

  private filterData = {
    // 公共条件
    common: [],
    // 我的筛选
    my: []
  };

  public setTableFilter (filters) {
    this.popoverShow = true;
    this.filterDetail('custom');
    this.custom.filters = [[getOption(filters)]];
  }

  public resetForm () {
    this.currentActive = {};
    this.editCondition = { filters: [] };
    this.reset();
  }

  private get searchType () {
    if (this.currentActive.id) {
      return { type: 'search', className: 'text' };
    } else if (!this.length) {
      return { type: 'empty', className: 'text-default' };
    }
    return { type: 'common', className: 'text-default' };
  }
  // table 中添加选项

  private get filterName () {
    if (this.currentActive.id === 'custom') {
      return flatten(this.currentActive.filters).length + '个筛选';
    } else if (this.currentActive.id) {
      return this.currentActive.filterName;
    }
    return '筛选';
  }

  // 所有条件都必须有businessId才能保存配置
  private get canSave () {
    return !flatten<any>(this.custom.filters || []).some((item) => {
      return !item.businessId;
    });
  }

  private get length () {
    return this.filterData.my.length + this.filterData.common.length;
  }

  public close () {
    this.resetForm()
    this.$emit('search', {});
  }

  private reset () {
    this.custom.filters = [[getOption()]];
  }

  private async searchById (item) {
    if (item.id === 'custom') {
      this.filterDetail('custom');
      return false;
    }
    // const res = await sheetAPI.filterCheck(item.id);
    // if (res.data) {
    //   this.edit(item.id, false);
    //   this.search(item);
    // } else {
    //   this.edit(item.id);
    // }
  }

  @Watch('custom.filters', { immediate: true })
  private filltersMenu (val) {
    if (val.length > 1) {
      emitter.emit('initFilter', val);
    } else if (val.length === 1) {
      if (val[0] && val[0][0].businessId) {
        emitter.emit('initFilter', val);
      } else {
        emitter.emit('initFilter', []);
      }
    }
  }

  // 筛选删除最后一条时 刷新列表
  @Watch('currentActive.filters.length')
  private changeFilterLength (val) {
    if (val === 0) {
      this.currentActive = {};
      this.editCondition = { filters: [] };
      this.$emit('search', {});
    }
  }

  // 返回
  private back () {
    this.editCondition = { filters: [] };
  }

  private async edit (id, popoverShow = true) {
    this.editCondition = { filters: [] };
    this.popoverShow = popoverShow;
    // const res = await sheetAPI.searchFilterById(id);
    // if (res.success) {
    //   this.editCondition = res.data;
    // }
  }

  private search (item, hiddenPopover: boolean = true) {
    if (item.id === 'custom' || this.editCondition.id) {
      if (isValide(item.filters)) {
        this.currentActive = item;
        this.$emit('search', { filters: this.currentActive.filters });
        emitter.emit('filterAll');
      } else {
        hiddenPopover = false;
      }
    } else {
      this.currentActive = item;
      this.$emit('search', { filterId: this.currentActive.id });
      emitter.emit('filterAll');
    }
    if (hiddenPopover) {
      this.popoverShow = false;
    }
  }

  private filterDetail (item) {
    this.popoverShow = true;
    if (item === 'custom') {
      this.reset();
      this.editCondition = { filters: [] };
      this.currentActive = this.custom;
      this.collapseOpen = '';
    } else {
      this.edit(item.id);
    }
  }

  private async updateBaseInfo (data) {
    // const res = await sheetAPI.updateBaseInfoFilter(data);
    // if (res.success) {
    //   if (this.editCondition.id) {
    //     this.editCondition = Object.assign({}, this.editCondition, data);
    //   }
    //   this.getFilterList();
    // }
  }

  private async copyFilter (id) {
    // const res = await sheetAPI.copyFilterById(id);
    // if (res.success) {
    //   this.getFilterList();
    // }
  }

  private async deleteFilter (id) {
    this.editCondition = { filters: [] };
    // const res = await sheetAPI.deleteFilterById(id);
    // if (res.success) {
    //   this.getFilterList();
    // }
  }

  private saveDialog () {
    if (this.canSave) {
      this.dialogObj.visible = true;
      this.dialogObj.form = { filterName: '', useScope: 1 };
    } else {
      // 筛选项不能为空
      this.$message.error('筛选项不能为空');
    }
  }

  private handleClose () {
    this.currentActive = {};
    this.$emit('search', {});
  }

  private handleCommand (item, command) {
    const { id, useScope } = item;
    if (command === 'edit') {
      this.edit(id);
    } else if (command === 'copy') {
      this.copyFilter(id);
    } else if (command === 'my' || command === 'common') {
      this.updateBaseInfo({ id, useScope: useScope === 1 ? 2 : 1 });
    } else if (command === 'delete') {
      this.deleteFilter(id);
    }
  }

  private async getFilterList () {
    // const res = await sheetAPI.searchFilterList(this.worksheetId);
    // if (res.success) {
    //   const common: any = [];
    //   const my: any = [];
    //   res.data.forEach((item) => {
    //     if (item.useScope === 1) {
    //       my.push(item);
    //     } else {
    //       common.push(item);
    //     }
    //   });
    //   this.filterData.common = common;
    //   this.filterData.my = my;
    // }
  }

  private submitSave () {
    (this.$refs.form as any).validate(async (valid) => {
      if (!valid) {
        return false;
      }
      // const { filters } = this.custom;
      // const { useScope, filterName } = this.dialogObj.form;
      // const data = {
      //   worksheetId: this.worksheetId,
      //   filters,
      //   useScope,
      //   screenType: 1,
      //   filterName
      // };
      // const res = await sheetAPI.addFilter(data);
      // if (res.success) {
      //   this.reset();
      //   this.getFilterList();
      //   this.collapseOpen = '1';
      //   this.dialogObj.visible = false;
      // }
    });
  }

  private mounted () {
    this.getFilterList();
  }

  private a () {
    this.currentActive = {};
    // 为了清空选中状态页面状态
    this.$emit('search-close', {});
    this.editCondition = { filters: [] };
  }

  private created () {
    emitter.on('quickFilter', this.a); // listen
  }

  private destroyed () {
    emitter.off('quickFilter', this.a); // unlisten
  }
}
</script>

<style lang="stylus" scoped>
.V7_iconV7tubiao_guanbi {
  font-size 12px
  margin-left: 4px
}
.filter-reference {
	flex-shrink 0
}
.wrap {
	color #000
	max-height 650px
	display flex
	margin 0 16px
	flex-direction column
	overflow-y hidden
}
.filter-title {
	display flex
	align-items center
	padding 16px 0
	justify-content space-between
	border-bottom 1px solid rgba(0, 0, 0, 0.05)
}
.search {
	background-color $back-main
	padding 0px 8px
	height 28px
	/deep/span {
		display inline-flex
		align-items center
		.iconshaixuan2-xian {
			box-sizing border-box
		}
	}
}
.common, .empty {
	color rgba(0,0,0, 0.6)
}
.footer {
	border-bottom 1px solid rgba(0, 0, 0, 0.05)
	padding 16px 0
}
.condition.filter {
	flex-shrink 2
	overflow-y auto
	padding 16px 0 8px
	border-bottom 1px solid rgba(0, 0, 0, 0.05)
}
.collapse {
	margin 16px 0
	/deep/.el-collapse-item__header {
		background rgba(0, 0, 0, 0.03)
		height 36px
		font-weight normal
		line-height 36px
		padding-left 16px
	}
	border-radius 4px
	/deep/.el-collapse-item__wrap {
		padding 0 16px 8px
		background rgba(0, 0, 0, 0.03)
	}
	/deep/.el-collapse-item__content {
		padding-bottom 0
	}
}
.btn-group {
	display flex
	flex-wrap wrap
	align-items center
	.condtion-btn {
		margin-right 16px
		margin-bottom 8px
		background rgba(0, 0, 0, 0.05)
		border-radius 2px
		display flex
		.name {
			line-height 28px
			padding 0 8px
		}
		/deep/.el-dropdown {
			border-left 1px solid #fff
			padding 0 4px
		}
		.icongengduo-heng {
			display block
		}
	}
}
.el-dropdown-menu__item {
	display flex
	align-items center
	span {
		flex-grow 1
	}
	.iconshezhi-xian {
		height 16px
		line-height 16px
		display none
	}
	&:hover {
		.iconshezhi-xian {
			display block
		}
	}
}
.screen-button {
	padding 10px 24px
}
</style>
